﻿using Newtonsoft.Json;
using ShiQuan.TcpServer;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinTest
{
    public class FrmMain : Form
    {
        private StatusStrip sysStatusBar;
        private ToolStripStatusLabel sysStatusLabel;
        private ToolStripStatusLabel sysStatusDate;
        private GroupBox groupBox1;
        private TextBox txtPort;
        private Label label2;
        private Button btnConnect;
        private NotifyIcon sysNotifyIcon;
        private Panel panelLeft;
        private Panel panelMain;
        private TabControl tabControl1;
        private TabPage tabPage1;
        private RichTextBox richTextBox1;
        private Splitter splitter2;
        private RichTextBox richTextBox2;

        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源，为 true；否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmMain));
            this.sysStatusBar = new System.Windows.Forms.StatusStrip();
            this.sysStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
            this.sysStatusDate = new System.Windows.Forms.ToolStripStatusLabel();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.btnConnect = new System.Windows.Forms.Button();
            this.txtPort = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.sysNotifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
            this.panelLeft = new System.Windows.Forms.Panel();
            this.panelMain = new System.Windows.Forms.Panel();
            this.tabControl1 = new System.Windows.Forms.TabControl();
            this.tabPage1 = new System.Windows.Forms.TabPage();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.splitter2 = new System.Windows.Forms.Splitter();
            this.richTextBox2 = new System.Windows.Forms.RichTextBox();
            this.sysStatusBar.SuspendLayout();
            this.groupBox1.SuspendLayout();
            this.panelLeft.SuspendLayout();
            this.panelMain.SuspendLayout();
            this.tabControl1.SuspendLayout();
            this.tabPage1.SuspendLayout();
            this.SuspendLayout();
            // 
            // sysStatusBar
            // 
            this.sysStatusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.sysStatusLabel,
            this.sysStatusDate});
            this.sysStatusBar.Location = new System.Drawing.Point(0, 539);
            this.sysStatusBar.Name = "sysStatusBar";
            this.sysStatusBar.Size = new System.Drawing.Size(784, 22);
            this.sysStatusBar.SizingGrip = false;
            this.sysStatusBar.TabIndex = 0;
            this.sysStatusBar.Text = "statusStrip1";
            // 
            // sysStatusLabel
            // 
            this.sysStatusLabel.Name = "sysStatusLabel";
            this.sysStatusLabel.Size = new System.Drawing.Size(649, 17);
            this.sysStatusLabel.Spring = true;
            this.sysStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // sysStatusDate
            // 
            this.sysStatusDate.AutoSize = false;
            this.sysStatusDate.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Right)));
            this.sysStatusDate.Name = "sysStatusDate";
            this.sysStatusDate.Size = new System.Drawing.Size(120, 17);
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.btnConnect);
            this.groupBox1.Controls.Add(this.txtPort);
            this.groupBox1.Controls.Add(this.label2);
            this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top;
            this.groupBox1.Location = new System.Drawing.Point(5, 5);
            this.groupBox1.Margin = new System.Windows.Forms.Padding(5);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(772, 55);
            this.groupBox1.TabIndex = 1;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "网络设置";
            // 
            // btnConnect
            // 
            this.btnConnect.Location = new System.Drawing.Point(201, 20);
            this.btnConnect.Name = "btnConnect";
            this.btnConnect.Size = new System.Drawing.Size(75, 23);
            this.btnConnect.TabIndex = 5;
            this.btnConnect.Text = "打开";
            this.btnConnect.UseVisualStyleBackColor = true;
            // 
            // txtPort
            // 
            this.txtPort.Location = new System.Drawing.Point(95, 22);
            this.txtPort.Name = "txtPort";
            this.txtPort.Size = new System.Drawing.Size(100, 21);
            this.txtPort.TabIndex = 3;
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 25);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(77, 12);
            this.label2.TabIndex = 1;
            this.label2.Text = "本地主机端口";
            // 
            // sysNotifyIcon
            // 
            this.sysNotifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("sysNotifyIcon.Icon")));
            this.sysNotifyIcon.Text = "notifyIcon1";
            this.sysNotifyIcon.Visible = true;
            // 
            // panelLeft
            // 
            this.panelLeft.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.panelLeft.Controls.Add(this.groupBox1);
            this.panelLeft.Dock = System.Windows.Forms.DockStyle.Top;
            this.panelLeft.Location = new System.Drawing.Point(0, 0);
            this.panelLeft.Name = "panelLeft";
            this.panelLeft.Padding = new System.Windows.Forms.Padding(5);
            this.panelLeft.Size = new System.Drawing.Size(784, 66);
            this.panelLeft.TabIndex = 4;
            // 
            // panelMain
            // 
            this.panelMain.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.panelMain.Controls.Add(this.tabControl1);
            this.panelMain.Controls.Add(this.splitter2);
            this.panelMain.Controls.Add(this.richTextBox2);
            this.panelMain.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panelMain.Location = new System.Drawing.Point(0, 66);
            this.panelMain.Name = "panelMain";
            this.panelMain.Size = new System.Drawing.Size(784, 473);
            this.panelMain.TabIndex = 7;
            // 
            // tabControl1
            // 
            this.tabControl1.Controls.Add(this.tabPage1);
            this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tabControl1.Location = new System.Drawing.Point(0, 0);
            this.tabControl1.Name = "tabControl1";
            this.tabControl1.SelectedIndex = 0;
            this.tabControl1.Size = new System.Drawing.Size(782, 365);
            this.tabControl1.TabIndex = 10;
            // 
            // tabPage1
            // 
            this.tabPage1.Controls.Add(this.richTextBox1);
            this.tabPage1.Location = new System.Drawing.Point(4, 22);
            this.tabPage1.Name = "tabPage1";
            this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
            this.tabPage1.Size = new System.Drawing.Size(774, 339);
            this.tabPage1.TabIndex = 0;
            this.tabPage1.Text = "数据接收";
            this.tabPage1.UseVisualStyleBackColor = true;
            // 
            // richTextBox1
            // 
            this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBox1.Location = new System.Drawing.Point(3, 3);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(768, 333);
            this.richTextBox1.TabIndex = 2;
            this.richTextBox1.Text = "";
            // 
            // splitter2
            // 
            this.splitter2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.splitter2.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.splitter2.Location = new System.Drawing.Point(0, 365);
            this.splitter2.Name = "splitter2";
            this.splitter2.Size = new System.Drawing.Size(782, 5);
            this.splitter2.TabIndex = 9;
            this.splitter2.TabStop = false;
            // 
            // richTextBox2
            // 
            this.richTextBox2.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.richTextBox2.Location = new System.Drawing.Point(0, 370);
            this.richTextBox2.Name = "richTextBox2";
            this.richTextBox2.Size = new System.Drawing.Size(782, 101);
            this.richTextBox2.TabIndex = 8;
            this.richTextBox2.Text = "";
            // 
            // FrmMain
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(784, 561);
            this.Controls.Add(this.panelMain);
            this.Controls.Add(this.panelLeft);
            this.Controls.Add(this.sysStatusBar);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Name = "FrmMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "华索物联网监听服务工具";
            this.sysStatusBar.ResumeLayout(false);
            this.sysStatusBar.PerformLayout();
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.panelLeft.ResumeLayout(false);
            this.panelMain.ResumeLayout(false);
            this.tabControl1.ResumeLayout(false);
            this.tabPage1.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion
        public FrmMain()
        {
            InitializeComponent();

            this.Load += FrmMain_Load;
        }
        private AsyncTcpServer server;
        private System.Timers.Timer sysTimer = new System.Timers.Timer();
        private System.Threading.Thread sysThread;
        private string webapiurl = string.Empty;
        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.Text = this.sysNotifyIcon.Text = Application.ProductName;
            this.SizeChanged += FrmMain_SizeChanged;
            this.sysNotifyIcon.DoubleClick += SysNotifyIcon_DoubleClick;
            this.sysNotifyIcon.Visible = true;

            this.sysStatusDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            this.sysTimer.Interval = 10000;//10秒
            this.sysTimer.Elapsed += SysTimer_Elapsed;
            this.sysTimer.Start();

            webapiurl = System.Configuration.ConfigurationManager.AppSettings["webapiurl"];
            var port = System.Configuration.ConfigurationManager.AppSettings["port"];
            this.txtPort.Text = port;

            this.btnConnect.Click += BtnConnect_Click;
            //this.btnExplain.Click += BtnExplain_Click;
            this.FormClosing += FrmMain_FormClosing;
        }

        private void FrmMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
                this.Hide();
        }

        private void SysNotifyIcon_DoubleClick(object sender, EventArgs e)
        {
            if (this.Visible == false)
            {
                this.Show();
            }
            this.WindowState = FormWindowState.Normal;
            this.Activate();
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.sysNotifyIcon.Dispose();
            this.sysTimer.Dispose();
            if (this.sysThread != null)
            {
                this.sysThread.Abort();
            }
            if (this.server != null)
            {
                this.server.Dispose();
            }
        }
        private void SysTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.sysStatusDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            if (sysThread != null && sysThread.ThreadState != System.Threading.ThreadState.Stopped)
            {
                return;
            }
            this.richTextBox2.Text = "";
            this.sysThread = new System.Threading.Thread(new System.Threading.ThreadStart(this.Explain));
            this.sysThread.IsBackground = true;
            this.sysThread.Start();
        }

        private void Explain()
        {
            try
            {
                var files = System.IO.Directory.GetFiles(Application.StartupPath + "\\Data", "*.db");
                if (files.Length <= 0)
                    return;

                for (int i = files.Length - 1; i >= 0; i--)
                {
                    var fileContent = System.IO.File.ReadAllText(files[i]);
                    if (string.IsNullOrEmpty(fileContent) || fileContent.Length <= 0)
                    {
                        System.IO.File.Delete(files[i]);
                        continue;
                    }
                    var lines = fileContent.Split('\n');
                    if (lines.Length <= 1)
                    {
                        System.IO.File.Delete(files[i]);
                        continue;
                    }
                    if (Explain(lines[1]) == false)
                        continue;
                    /*文件备份*/
                    System.IO.File.AppendAllText(Application.StartupPath + "\\Backup\\" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".db", fileContent);

                    System.IO.File.Delete(files[i]);/*删除文件*/
                }
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }

        }

        private bool Explain(string content)
        {
            try
            {
                var fieldValue = content.Split('&');
                var datetime = fieldValue[0];
                var values = fieldValue[1].Split(' ');
                //byte[] result = System.Text.Encoding.UTF8.GetBytes(content[1]);
                //byte[] result = HexStringToBytes(content[1]);
                if (Convert.ToInt32(values[2], 16) != 1)
                {
                    return false;
                }
                DeviceData deviceData = new DeviceData();
                deviceData.datetime = DateTime.Parse(datetime);
                deviceData.serialnumber = values[3] + values[4] + values[5] + values[6] + values[7] + values[8];
                deviceData.index = Convert.ToInt32(values[9] + values[10] + values[11] + values[12], 16);

                //temp = new byte[4];
                //Buffer.BlockCopy(result, 16, temp, 0, 4);
                //var pm25 = BitConverter.ToInt32(temp, 0);//pm25
                //data.AppendLine("pm25=" + length);
                var hexString = values[16] + values[17] + values[18] + values[19];
                var pm25 = Convert.ToInt32(hexString, 16);
                deviceData.data01 = pm25.ToString();

                //temp = new byte[4];
                //Buffer.BlockCopy(result, 20, temp, 0, 4);
                //var pm10 = BitConverter.ToInt32(temp, 0);//pm10
                hexString = values[20] + values[21] + values[22] + values[23];
                var pm10 = Convert.ToInt32(hexString, 16);
                //data.AppendLine("pm10 " + hexString + "=" + pm10);
                deviceData.data02 = pm10.ToString();

                //temp = new byte[4];
                //Buffer.BlockCopy(result, 24, temp, 0, 4);
                //var noise = BitConverter.ToSingle(temp, 0);//噪声
                hexString = values[24] + values[25] + values[26] + values[27];
                //uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
                //byte[] floatVals = BitConverter.GetBytes(num);
                //var noise = BitConverter.ToSingle(floatVals, 0);
                //var noise = Convert.ToUInt32(hexString, 16);
                var noise = Convert.ToInt32(hexString, 16);
                //data.AppendLine("噪声 " + hexString + "=" + noise / 10.0);
                deviceData.data03 = noise.ToString();

                //temp = new byte[4];
                //Buffer.BlockCopy(result, 28, temp, 0, 4);
                //var oc = BitConverter.ToSingle(temp, 0);//温度
                hexString = values[28] + values[29] + values[30] + values[31];
                //num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
                //floatVals = BitConverter.GetBytes(num);
                //var oc = BitConverter.ToSingle(floatVals, 0);
                var oc = Convert.ToInt32(hexString, 16);//字符串转16进制32位无符号整数
                //float oc = BitConverter.ToSingle(BitConverter.GetBytes(x), 0);//IEEE754 字节转换float
                //data.AppendLine("温度 " + hexString + "=" + oc / 10.0);
                deviceData.data04 = oc.ToString();

                //temp = new byte[4];
                //Buffer.BlockCopy(result, 32, temp, 0, 4);
                //var humidity = BitConverter.ToSingle(temp, 0);//湿度
                hexString = values[32] + values[33] + values[34] + values[35];
                //num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
                //floatVals = BitConverter.GetBytes(num);
                //var humidity = BitConverter.ToSingle(floatVals, 0);
                var humidity = Convert.ToUInt32(hexString, 16);
                //data.AppendLine("湿度 " + hexString + "=" + humidity / 10.0);
                deviceData.data05 = humidity.ToString();

                //temp = new byte[4];
                //Buffer.BlockCopy(result, 36, temp, 0, 4);
                //var eirection = BitConverter.ToInt32(temp, 0);//风向
                var eirection = Convert.ToInt32(values[36] + values[37] + values[38] + values[39], 16);
                //data.AppendLine("风向=" + eirection);
                deviceData.data06 = eirection.ToString();

                //temp = new byte[4];
                //Buffer.BlockCopy(result, 40, temp, 0, 4);
                //var airspeed = BitConverter.ToSingle(temp, 0);//风速
                hexString = values[40] + values[41] + values[42] + values[43];
                //num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
                //floatVals = BitConverter.GetBytes(num);
                //var airspeed = BitConverter.ToSingle(floatVals, 0);
                var airspeed = Convert.ToInt32(hexString, 16);
                //data.AppendLine("风速=" + airspeed / 10.0);
                deviceData.data07 = airspeed.ToString();

                //temp = new byte[4];
                //Buffer.BlockCopy(result, 44, temp, 0, 4);
                //var atmospheric = BitConverter.ToSingle(temp, 0);//大气压
                hexString = values[44] + values[45] + values[46] + values[47];
                //num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
                //floatVals = BitConverter.GetBytes(num);
                //var atmospheric = BitConverter.ToSingle(floatVals, 0);
                var oc02 = Convert.ToInt32(hexString, 16);
                //data.AppendLine("温度 " + hexString + "=" + oc02 / 10.0);
                deviceData.data08 = oc02.ToString();

                //temp = new byte[4];
                //Buffer.BlockCopy(result, 44, temp, 0, 4);
                //var atmospheric = BitConverter.ToSingle(temp, 0);//大气压
                hexString = values[48] + values[49] + values[50] + values[51];
                //num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
                //floatVals = BitConverter.GetBytes(num);
                //var atmospheric = BitConverter.ToSingle(floatVals, 0);
                var humidity02 = Convert.ToInt32(hexString, 16);
                //data.AppendLine("湿度 " + hexString + "=" + humidity02 / 10.0);
                deviceData.data09 = humidity02.ToString();

                //temp = new byte[4];
                //Buffer.BlockCopy(result, 48, temp, 0, 4);
                //var tsp = BitConverter.ToInt32(temp, 0);//tsp
                //data.AppendLine("tsp=" + length);

                //this.richTextBox2.Text = data.ToString();

                var jsonString = JsonConvert.SerializeObject(deviceData);
                this.AppendText02(jsonString);

                this.Upload(webapiurl, jsonString);
                return true;
            }
            catch (Exception ex)
            {
                this.Error(ex);
                return false;
            }
        }

        private void BtnExplain_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.richTextBox1.Text) || this.richTextBox1.Text == "")
            {
                MessageBox.Show("设备数据不能为空！");
                return;
            }
            var lines = this.richTextBox1.Text.Split('\n');
            if (lines.Length <= 1)
            {
                MessageBox.Show("设备数据不能为空！");
                return;
            }
            this.Explain(lines[1]);
        }

        private void BtnConnect_Click(object sender, EventArgs e)
        {
            if (this.btnConnect.Text == "打开")
            {
                Cursor = Cursors.WaitCursor;
                try
                {
                    int port = 80;
                    int.TryParse(this.txtPort.Text, out port);
                    if (port <= 0)
                        port = 80;

                    server = new AsyncTcpServer(port);
                    server.Encoding = Encoding.UTF8;
                    server.ClientConnected += Server_ClientConnected;
                    server.ClientDisconnected += Server_ClientDisconnected;
                    server.ClientReceived += Server_ClientReceived;
                    //server.PlaintextReceived += Server_PlaintextReceived;
                    server.Start();

                    //Console.WriteLine("TCP server has been started.");
                    //Console.WriteLine("Type something to send to client...");
                    //while (true)
                    //{
                    //    string text = Console.ReadLine();
                    //    server.SendAll(text);
                    //}
                    this.txtPort.Enabled = false;
                    this.richTextBox1.Text = "";
                    this.btnConnect.Text = "关闭";
                    this.sysStatusLabel.Text = "服务器打开！";
                }
                catch (Exception ex)
                {
                    this.Error(ex);
                }
                finally
                {
                    Cursor = Cursors.Default;

                }
            }
            else
            {
                Cursor = Cursors.WaitCursor;
                try
                {
                    this.server.Dispose();
                    this.txtPort.Enabled = true;
                    this.btnConnect.Text = "打开";
                    this.sysStatusLabel.Text = "服务器关闭！";
                }
                catch (Exception ex)
                {
                    this.Error(ex);
                }
                finally
                {
                    Cursor = Cursors.Default;

                }
            }
        }

        private void Server_ClientReceived(object sender, TcpClientReceivedEventArgs<byte[]> e)
        {
            try
            {
                StringBuilder msg = new StringBuilder();
                msg.AppendLine(e.TcpClient.Client.RemoteEndPoint.ToString());
                msg.AppendLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "&" + BitConverter.ToString(e.Datagram).Replace("-", " "));

                System.IO.File.WriteAllText(Application.StartupPath + "\\data\\" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".db", msg.ToString(), System.Text.Encoding.UTF8);

                //this.richTextBox1.AppendText(msg.ToString());
                //this.richTextBox1.ScrollToCaret();
                this.AppendText(msg.ToString());
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }

        }


        private void Server_PlaintextReceived(object sender, TcpClientReceivedEventArgs<string> e)
        {
            try
            {
                StringBuilder msg = new StringBuilder();
                msg.AppendLine(DateTime.Now.ToString("yyyyMMdd-HHmmss") + ":" + e.TcpClient.Client.RemoteEndPoint.ToString());
                msg.AppendLine(e.Datagram);

                System.IO.File.WriteAllText("data\\" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".db", msg.ToString(), System.Text.Encoding.UTF8);

                //this.AppendText(msg.ToString());
                this.richTextBox1.AppendText(msg.ToString());
                this.richTextBox1.ScrollToCaret();
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }
        }
        private void Server_ClientDisconnected(object sender, TcpClientDisconnectedEventArgs e)
        {
            this.AppendText(DateTime.Now.ToString("yyyyMMdd-HHmmss") + ":" + e.TcpClient.Client.RemoteEndPoint.ToString() + " disconnected!\n");
        }

        private void Server_ClientConnected(object sender, TcpClientConnectedEventArgs e)
        {
            this.AppendText(DateTime.Now.ToString("yyyyMMdd-HHmmss") + ":" + e.TcpClient.Client.RemoteEndPoint.ToString() + " connected!\n");
        }

        private delegate void OnAppendText(string msg);
        private void AppendText(string msg)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                OnAppendText appendText = new OnAppendText(this.AppendText);
                //appendText.Invoke(msg);
                this.Invoke(appendText, new object[] { msg });
            }
            else
            {
                this.richTextBox1.AppendText(msg);
                this.richTextBox1.ScrollToCaret();
            }
        }

        private void AppendText02(string msg)
        {
            if (this.richTextBox2.InvokeRequired)
            {
                OnAppendText appendText = new OnAppendText(this.AppendText02);
                //appendText.Invoke(msg);
                this.Invoke(appendText, new object[] { msg });
            }
            else
            {
                this.richTextBox2.AppendText(msg);
                this.richTextBox2.ScrollToCaret();
            }
        }

        private void Error(Exception ex)
        {
            System.IO.File.AppendAllText(Application.StartupPath + "\\Error\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".db", ex.ToString() + "\n");
            //MessageBox.Show("异常：" + ex.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.AppendText02("异常：" + ex.Message);
        }

        /// <summary>  
        /// 调用api返回json  
        /// </summary>  
        /// <param name="url">api地址</param>  
        /// <param name="jsonstr">接收参数</param>  
        /// <param name="type">类型</param>  
        /// <returns></returns>  
        public string HttpRequest(string url, string jsonstr, string type)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址  
            request.Accept = "text/html,application/xhtml+xml,*/*";
            request.ContentType = "application/json";
            request.Method = type.ToUpper().ToString();//get或者post  
            byte[] buffer = encoding.GetBytes(jsonstr);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        private void Upload(string url, string jsonData)
        {
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("entity", jsonData);

            //创建WebClient 对象
            WebClient web = new WebClient();
            //采取POST方式必须加的header，如果改为GET方式的话就去掉这句话即可
            web.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            //转化为二进制数据
            //byte[] postData = Encoding.UTF8.GetBytes(jsonData);
            //上传数据
            byte[] responseData = web.UploadValues(url, "POST", nvc);

            //服务器返回的数据
            var result = Encoding.UTF8.GetString(responseData);
            this.AppendText02(result);
        }

        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string ByteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2") + " ";
                }
            }
            return returnStr;
        }

        /// <summary>
        /// 16进制原码字符串转字节数组
        /// </summary>
        /// <param name="hexString">"AABBCC"或"AA BB CC"格式的字符串</param>
        /// <returns></returns>
        public static byte[] HexStringToBytes(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if (hexString.Length % 2 != 0)
            {
                throw new ArgumentException("参数长度不正确");
            }

            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
            {
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
            return returnBytes;
        }
    }
}
